package com.rtx.express.handle;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rtx.api.annotation.DataSourceAnnotation;
import com.rtx.edi.model.api.bo.ApiMappingInfoBo;
import com.rtx.edi.model.express.bo.ExpressBO;
import com.rtx.edi.model.express.po.PlExpressApi;
import com.rtx.edi.model.express.po.PlExpressApiConfig;
import com.rtx.edi.model.express.po.PlExpressResult;
import com.rtx.edi.platform.baseinfo.service.PlApiService;
import com.rtx.edi.platform.express.config.service.PlExpressApiConfigService;
import com.rtx.wms.std.common.bean.Codelkup;
import com.rtx.wms.std.common.service.CommonService;
import com.rtx.wms.std.express.bean.ExpressOrders;
import com.rtx.wms.std.express.service.ExpressResultService;
import com.rtx.wms.std.so.bean.Orders;
import com.rtx.wms.std.so.service.OrdersService;

@Service
public class ExpressCollectHandle {
	
	
	@Autowired
	PlExpressApiConfigService plExpressApiConfigService;
	
	@Autowired
	OrdersService ordersService;
	
	@Autowired
	CommonService commonService;
	
	@Autowired
	ExpressResultService expressResultService;
	
	@Autowired
	PlApiService plApiService;
	
	
	
	/**
	 * 	通过出库单号 获取写入快递任务表信息
	 * @param orderkey 出库单单号
	 * @param expressTypePrefix 接口类型
	 */
	@DataSourceAnnotation
	public ExpressBO collectExpressInfoByOrderkey(String wmwhse1,String orderkey,ExpressBO bo,ApiMappingInfoBo ediConfig) {
		//获取出库单信息
		QueryWrapper<Orders> oqw = new QueryWrapper<Orders>();
		oqw.eq("orderkey", orderkey);
		List<Orders> ordersList =  ordersService.selectOrdersByWrapper(bo.getWmwsheid(), oqw);
		Orders orders = ordersList.get(0);
		
		//获取配置信息
		PlExpressApiConfig  config = null;
		if(ediConfig == null) {
			config = queryConfig(bo,orders);
		}else {
			config = ediConfig.getExpressconfig();
		}
				
		bo.setExpressConfig(config);
		
		//填充取快递单号必须数据
		PlExpressApi task = mappingExpressTaskEntity(orders,config);
		bo.setExpressTask(task);
		
		
		//映射配置文件中的信息
		mappingSendInforByConfig(config,task);
		
		//德邦获取
		mappingDpoponzd(bo,orders);
		
		return bo;
	}
	
	private PlExpressApi mappingExpressTaskEntity(Orders orders,PlExpressApiConfig config){
		PlExpressApi task = new PlExpressApi();
		task.setExternorderkey(orders.getExternorderkey());
		task.setCarrierCode(orders.getCarriercode());
		task.setOrderkey(orders.getOrderkey());
		
		//唯品快递单号
		task.setExpresscode(orders.getRtxexpresskey());

		//映射发货地址
		mappingSendInfor(orders,task);
		
		//映射收件人地址
		mappingReceived(task,orders);
		
		//映射线下快递接口信息
		mappingCarrierer(task,orders);
		
		//映射线上平台快递接口信息
		mappingRtxsalesp(task,orders,config);
		

		return task;
	}
	
	private PlExpressApiConfig queryConfig(ExpressBO bo,Orders orders) {
		LambdaQueryWrapper<PlExpressApiConfig> qw = Wrappers.lambdaQuery();
		List<PlExpressApiConfig> list = plExpressApiConfigService.selectList("ris_edi",qw);
		String rtxsalesp = orders.getRtxsalesp();
		String carriercode = orders.getCarriercode();
		String storerkey = orders.getStorerkey();
		
		String unikey =storerkey+carriercode+rtxsalesp;
		
		List<PlExpressApiConfig> filter = list.stream().filter(temp->unikey.equals(temp.getStorerkey()+temp.getCarriercode()+temp.getRtxsalesp())).collect(Collectors.toList());
		
		PlExpressApiConfig config = null;
		if(filter.size()<1) {
			throw new RuntimeException("出库单货主-storerkey-"+storerkey+"-承运商编码carriercode-"+carriercode+"-平台编码-"+rtxsalesp+"-在express_mapping_config未配置快递接口API匹配关系！");
		}else {
			config = filter.get(0);
		}
		
		return config;
	}
	
	/**
	 * 	映射发货地址
	 * @param task
	 */
	void mappingSendInfor(Orders orders,PlExpressApi task) {
		//获取各个仓库发货地址
		QueryWrapper<Codelkup> sendQw = new QueryWrapper<Codelkup>();
		sendQw.eq("listname", "SENDERINFO");
		List<Codelkup> sendList = commonService.selectCodelkupByWrapper(orders.getWhseid(),sendQw);
		Map<String,String> sendMap = new HashMap<String, String>();
		for(Codelkup send:sendList) {
			sendMap.put(send.getCode(), send.getUdf1());
		}
		
		
		task.setSendAddress(sendMap.get("DETAILADDRESS"));
		task.setSendCity(sendMap.get("CITY"));
		task.setSendCompanyName("");
		task.setSendCounty(sendMap.get("AREA"));
		task.setSendMobile(sendMap.get("MOBILE"));
		task.setSendName(sendMap.get("NAME"));
		task.setSendPhone(sendMap.get("TEL"));
		task.setSendProvince(sendMap.get("PROVINCE"));
		task.setSendTown("");
	}
	
	/**
	 * 	匹配配置信息
	 * @param task
	 */
	void mappingSendInforByConfig(PlExpressApiConfig config,PlExpressApi task) {
		
		
		//平台承运商代码
		task.setMappingCarriercode(config.getPlatformCarriercode());
		//模板
		task.setTemplatesurl(config.getTemplatesurl());
		//平台承运商代码
		task.setPlatformCarriercode(config.getPlatformCarriercode());
		
		//发货地址如果配置表中有值, 则获取配置表中的值
		if(StringUtils.hasLength(config.getSendAddress())) {
			task.setSendAddress(config.getSendAddress());
		}	
		if(StringUtils.hasLength(config.getSendCity())) {
			task.setSendCity(config.getSendCity());
		}
		if(StringUtils.hasLength(config.getSendCompanyName())) {
			task.setSendCompanyName(config.getSendCompanyName());
		}
		if(StringUtils.hasLength(config.getSendCounty())) {
			task.setSendCounty(config.getSendCounty());
		}
		if(StringUtils.hasLength(config.getSendMobile())) {
			task.setSendMobile(config.getSendMobile());
		}
		if(StringUtils.hasLength(config.getSendName())) {
			task.setSendName(config.getSendName());
		}
		if(StringUtils.hasLength(config.getSendPhone())) {
			task.setSendPhone(config.getSendPhone());
		}
		if(StringUtils.hasLength(config.getSendProvince())) {
			task.setSendProvince(config.getSendProvince());
		}
		if(StringUtils.hasLength(config.getSendTown())) {
			task.setSendTown(config.getSendTown());
		}
	}
	
	
	/**
	 * 	映射收件人信息
	 * @param task
	 * @param orders
	 */
	void mappingReceived(PlExpressApi task,Orders orders) {
		task.setReceiverAddress(orders.getCAddress1());
		task.setReceiverCity(orders.getCCity());
		task.setReceiverCompanyName("");
		task.setReceiverCounty(orders.getCCountry());
		task.setReceiverMobile(orders.getCPhone1());
		task.setReceiverName(orders.getCContact1());
		task.setReceiverPhone(orders.getCPhone1());
		task.setReceiverProvince(orders.getCState());
		task.setReceiverTown(orders.getDefault01());
	}
	
	/**
	 * 映射API编码
	 * @param orders
	 * @param expressTypePrefix
	 * @return
	 */
	void mappingExpressConfigId(PlExpressApi task,PlExpressApiConfig config) {
		task.setExpressType(config.getExpressapi());
	}
	
	/**
	 * 映射线下快递接口信息
	 */
	void mappingCarrierer(PlExpressApi task,Orders orders) {
		//映射德邦快递接口信息
		mappingDpoponField(task);
//		//映射顺丰快递接口信息
//		mappingSFField(task);
//		//映射春风物流快递接口信息
//		mappingCFField(task);
//		//映射申通快递接口信息
//		mappingSTOField(task);
//		//映射中通快递接口信息
//		mappingZTOField(task);
	}
	
	/**
	 * 映射线上平台快递接口信息
	 * @param task
	 */
	void mappingRtxsalesp(PlExpressApi task,Orders orders,PlExpressApiConfig config) {
		//平台单号
		task.setTid(orders.getTid());
		
		
		//映射淘系快递接口信息
		mappingTMField(task,orders,config);
		//映射抖音
		mappingDYXDField(task,orders,config);
		//唯品会线上
		mappingWPHField(task,orders,config);
	}
	
	
	/**
	 * 设置德邦快递接口参数
	 * @param task
	 */
	void mappingDpoponField(PlExpressApi task){
		task.setDpopenTransportType("");
	}
	
	/**
	 * 设置顺丰快递接口参数
	 * @param task
	 */
	void mappingSFField(PlExpressApi task){
	}
	/**
	 * 设置春风物流快递接口参数
	 * @param task
	 */
	void mappingCFField(PlExpressApi task){
	}
	
	/**
	 * 设置申通快递接口参数
	 * @param task
	 */
	void mappingSTOField(PlExpressApi task){
	}
	/**
	 * 设置中通快递接口参数
	 * @param task
	 */
	void mappingZTOField(PlExpressApi task){
	}
	/**
	 * 设置淘系平台快递接口参数
	 * @param task
	 */
	void mappingTMField(PlExpressApi task,Orders orders,PlExpressApiConfig config){
		if("TM".equals(config.getExpressapi())) {
			task.setOaid(orders.getOaid());
			if("SF".equals(config.getPlatformCarriercode())) {
				task.setBrandcode("SF");
				task.setProductCode("247");//顺丰特惠
			}else {
				task.setBrandcode("default");
			}
			
			if(Arrays.asList("TM,TB".split(",")).contains(config.getRtxsalesp())) {
				config.setChannelsType("TB");
			}else {
				config.setChannelsType("OTHERS");
			}
			
			//暇步士线上换货单逻辑
			//default10 来源为出库单下发request.deliveryOrder.oaidOrderSourceCode 当该字段有值且需要获取快递单号时 
			//假如oaidOrderSourceCode值与sourceOrderCode 不相同 通过oaidOrderSourceCode 获取菜鸟接口快递单号
			if(StringUtils.hasLength(orders.getDefault10())) {
				task.setTid(orders.getDefault10());
			}
		}
	}
	
	void mappingPDDField(PlExpressApi task,ExpressOrders orders,PlExpressApiConfig config){
		if("PDD".equals(config.getExpressapi())) {

		}
	}
	
	void mappingDYXDField(PlExpressApi task,Orders orders,PlExpressApiConfig config){
		if("DY".equals(config.getExpressapi())) {
			task.setProductCode("247");//顺丰特惠
		}
	}
	
	//暇步士唯品重新获取单号
	void mappingWPHField(PlExpressApi task,Orders orders,PlExpressApiConfig config){
	};
	
	//德邦获取子单号配置
	private void mappingDpoponzd(ExpressBO bo,Orders orders) {
		if(bo.getZdflag()&&"DBKD".equals(bo.getExpressConfig().getExpressapi())) {
			LambdaQueryWrapper<PlExpressResult> qw = Wrappers.lambdaQuery();
			qw.eq(PlExpressResult::getExternorderkey, bo.getExpressTask().getExternorderkey()).last("limit 1");
			List<PlExpressResult> list =Optional.ofNullable(expressResultService.selectByWrappers(bo.getWmwsheid(), qw)).orElse(new ArrayList<PlExpressResult>());
			PlExpressResult plExpressResult =Optional.ofNullable(list.get(0)).orElse(new PlExpressResult()) ;
			bo.getExpressTask().setLogisticid(plExpressResult.getDpoponlogisticID());
			bo.getExpressTask().setNotes(orders.getNotes());
			bo.setDpopondefault08(orders.getDefault08());
		}

	}
	
}
